﻿using System;
using System.Linq;
using System.Reflection;
using NSubstitute;
using Phoenix;
using Phoenix.Frames;
using Phoenix.Framework;
using Phoenix.Lifetime;

// ReSharper disable CheckNamespace
public static class Extensions
{
    public static T Initialise<T>(this T controller, string actionName) where T : Controller
    {
        var controllerType = typeof(T);
        var controllerAction = new ControllerAction(controllerType.Name, actionName, controllerType.Assembly.FullName);
        var controllerActionContext = new ControllerActionContext(controllerAction, Substitute.For<INavigationFrame>(),
            Substitute.For<IContentFrame>(),
            Substitute.For<IPhoenixHost>(),
            new RequestTransientStore(),
            Enumerable.Empty<ControllerActionParameter>(),
            InvokeOptions.None);
        controller.Initialise(controllerActionContext);

        return controller;
    }

    public static void AssertCanResolveAllViews(
        this Assembly assembly,
        IViewLocator usingLocator = null,
        IControllerLocator controllerLocator = null)
    {
        if (usingLocator == null)
            usingLocator = new DefaultViewLocator(assembly);
        else
            usingLocator.AddAssemblyToScan(assembly);

        if (controllerLocator == null)
            controllerLocator = new DefaultControllerLocator(assembly);
        else
            controllerLocator.AddAssemblyToScan(assembly);

        foreach (var controllerType in controllerLocator.GetControllersInAssembly(assembly))
        {
            foreach (var actionName in controllerType.GetMethods())
            {
                usingLocator.Locate(new ControllerAction(controllerType.Name, actionName.Name, assembly.FullName));
            }
        }
    }
}

// ReSharper restore CheckNamespace